var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/web/index');

//导入express-session模块和connect-mongo模块
const session = require('express-session');
const MongoStore = require('connect-mongo');

//导入配置文件
const{url,port,db} = require('./config/config');

//导入 users 路由文件
const authRouter = require('./routes/web/auth');

//导入 auth的 API 路由文件
const authApiRouter = require('./routes/api/auth');

//导入 account 接口路由文件 
var accountRouter = require('./routes/api/account');

var app = express();

//使用 session 中间件
app.use(session({
  name: 'sid', // 设置 cookie 中保存 session id 的字段名称
  secret: 'atguigu',
  saveUninitialized: false, // 是否在存储内容之前创建会话
  resave: true, // 强制重新保存 session 即使它并没有变化
  store: MongoStore.create({
    mongoUrl: `${url}:${port}/${db}`,
  }),
  cookie: {
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24 // 设置 session 的有效时间，单位毫秒
  },
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
// 使用注册登录路由文件;
app.use('/', authRouter);
// 使用 account 接口路由文件
app.use('/api', accountRouter);
//使用authApiRouter
app.use('/api', authApiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  //响应404页面
  res.render('404');
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
